import { getRouters } from "@/api/menu.js"

const permission = {
  state: {
    // 请求到的路由
    routes: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.routes = routes
    },
  },
  actions: {
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        getRouters().then((res) => {
          const sdata = JSON.parse(JSON.stringify(res.data))
          const rdata = JSON.parse(JSON.stringify(res.data))
          commit("SET_ROUTES", sdata)
          const rewriteRoutes = setProcessMenu(rdata);
          resolve(rewriteRoutes);
        });
      });
    }
  }
}

function setProcessMenu(menus) {
  // 判断是否有菜单数据
  if (menus) {
    // 拼装动态路由
    const manageRoute = {
      path: '/manageRoute',
      component: () => import('@/components/layout/Main.vue'),
      // 重定向
      redirect: '/home',
      name: 'manageRoute',
      // 子路由
      children: []
    }
    processMenu(menus, manageRoute)

    // 返回数据
    return manageRoute
  }
}

// 递归函数，用于处理嵌套的目录路由
function processMenu(childrens, manageRoute) {
  childrens.map(item => {
    const router = {
      path: "/" + item.path,
      name: item.name,
      component: () => import(`@/views/${item.component}.vue`),
      children: []
    }

    if (item.children != null && item.children.length > 0) {
      processMenu(item.children, manageRoute)
    }
    manageRoute.children.push(router);
  })
}


export default permission;